<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/10/26
 * Time: 13:40
 */

namespace app\Service;


use app\api\model\Sns\SnsModel;
use think\cache\driver\Redis;
use think\Db;

class SnsService extends BaseService
{

    protected $redis;

    /**
     * @param $data
     * @return bool
     * 关注
     */

    function __construct()
    {
        $this->redis = new Redis();
    }

    public function addFollowsFansById($data): bool
    {
        if (empty($data)) return false;
        $data['sns_addtime'] = time();
        if ($data['sns_followstate'] == 1) {//单方面关注
            $result = $this->addFollowFan($data);//添加到数据库
            return true;
        } elseif ($data['sns_followstate'] == 2) {//相互关注
            //开启事务
            Db::transaction(function () use ($data) {
                $this->addFollowFan($data);
                return true;
            });
        } else {
            return false;
        }
    }

    /**
     * @param $user_id
     * @param $follow_id
     * @param $state
     * @return bool
     * 取消关注
     */
    public function deleteFollowFansById($user_id, $follow_id, $state): bool
    {
        if ($state == 1) {
            $result = $this->deleteFollowFans(['sns_frommid' => $user_id, 'sns_tomid' => $follow_id]);
            return true;
        } elseif ($state == 2) {
            //开启事务
            Db::transaction(function () use ($user_id, $follow_id) {
                $this->deleteFollowFans(['sns_frommid' => $user_id, 'sns_tomid' => $follow_id]);
                $this->editFollowFans(['sns_frommid' => $follow_id, 'sns_tomid' => $user_id], ['sns_followstate' => 1]);
            });
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param array $data
     * 删除关注
     */
    protected function deleteFollowFans(array $data)
    {
        return SnsModel::where($data)->delete();
    }

    /**
     * 相互关注
     */
    protected function editFollowFans(array $data)
    {
//        ['sns_frommid' => $data['sns_tomid'], 'sns_tomid' => $data['sns_frommid']], ['sns_followstate' => 2];
        Db::name('sns')->update();

    }

    /**
     * @param array $data
     * @return int|string
     * 添加粉丝
     */
    public function addFollowFan(array $data)
    {
        return Db::name('sns')->insert($data);
    }
}